﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf2.Models;
using Wpf2.ViewModels;

namespace Wpf2.Views
{
    /// <summary>
    /// Interaction logic for formEditExportOrder.xaml
    /// </summary>
    public partial class FormEditExportOrder 
    {
        bool _canExcuteTextChangedEvent = true;

        editExportOrderViewModel _exportViewModel;
        
        public FormEditExportOrder(int iOrderID)
        {
            try
            {
                InitializeComponent();
                _exportViewModel = new editExportOrderViewModel(iOrderID);
                OverrideEventOfDataGird();
                DataContext = _exportViewModel;
                if(!_exportViewModel.IsMarcle)
                    hideColumnOfMarcle();
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }


        /// <summary>
        /// Ẩn 3 cột liên quan đế Đá Hoa Cương
        /// </summary>
        private void hideColumnOfMarcle()
        {
            dtgInventory.Columns[3].Visibility = System.Windows.Visibility.Hidden;
            dtgInventory.Columns[4].Visibility = System.Windows.Visibility.Hidden;
            dtgInventory.Columns[6].Visibility = System.Windows.Visibility.Hidden;
        }

    #region --- xử lý liên quan đến datagrid ---
        private void OverrideEventOfDataGird()
        {
            dtgInventory.LoadingRow += dtgInventory_LoadingRow;
            dtgInventory.RowEditEnding += DtgInventoryRowEditEnding;
        }

        private void DtgInventoryRowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            _exportViewModel.addNewProduct();
        }

        private void dtgInventory_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }
    #endregion

    #region --- xử lý liên quan đến giao diện (autocomplete,,,,) ---


        private void TxtProductNameTextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (!_canExcuteTextChangedEvent || !IsLoaded) // specify is event can run or not
                    return;
                var txtProductName = sender as TextBox;
                if (txtProductName != null)
                {
                    var p = txtProductName.DataContext as Products;
                    if (p != null && !string.IsNullOrEmpty(p.ProductName)) // if text's textbox change when exist Product was binded => delete Product and create new Product to find
                    {
                        int index = _exportViewModel.ListProducts.IndexOf(p);
                        _exportViewModel.ListProducts.RemoveAt(index);
                        _exportViewModel.ListProducts.Insert(index, new Products());
                        return;
                    }
                }
                if (txtProductName == null) return;
                var stp = txtProductName.Parent as Grid;
                if (stp == null) return;
                var cmbListToChoose = stp.Children[1] as ComboBox;
                if (cmbListToChoose == null) return;
                cmbListToChoose.Items.Clear();

                LoadComboboxItem(txtProductName.Text, cmbListToChoose);

                if (cmbListToChoose.HasItems)
                    cmbListToChoose.IsDropDownOpen = true;
                else
                    cmbListToChoose.IsDropDownOpen = false;
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        private void LoadComboboxItem(string searchString, ComboBox comboboxResult)
        {
            try
            {
                foreach (var cbItem in from item in _exportViewModel.ObsProducts where !string.IsNullOrEmpty(searchString) where !IsExistInProductList(_exportViewModel.ListProducts, item) where item.ProductId.StartsWith(searchString, StringComparison.CurrentCultureIgnoreCase) select new ComboBoxItem {Content = item.ProductId, Tag = item.ProductIdAuto})
                    comboboxResult.Items.Add(cbItem);
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }
        }

        private static bool IsExistInProductList(IEnumerable<Products> productList, Products product)
        {
            return productList.Any(item => item.ProductId == product.ProductId);
        }

        private void TxtProductNameLostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                var txtProductName = sender as TextBox;
                if (txtProductName == null) return;
                var stp = txtProductName.Parent as Grid;
                if (stp == null) return;
                var cmbListToChoose = stp.Children[1] as ComboBox;
                if (cmbListToChoose != null) cmbListToChoose.IsDropDownOpen = false;
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }
        }

        private void ComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                _canExcuteTextChangedEvent = false; // when get content's Commbobox to set text's textbox => TextChanged will be excuted => stop event
                var cmbListToChoose = sender as ComboBox;
                if (cmbListToChoose != null)
                {
                    var stp = cmbListToChoose.Parent as Grid;
                    if (stp != null)
                    {
                        var txtProductName = stp.Children[0] as TextBox;
                        var cbItem = (ComboBoxItem)cmbListToChoose.SelectedItem;
                        if (txtProductName != null)
                        {
                            var p = txtProductName.DataContext as Products;

                            var np = WPFServices.Services.Products.GetProduct(int.Parse(cbItem.Tag.ToString()));

                            if (null != cmbListToChoose.SelectedItem)
                            {
                                if (p != null)
                                {
                                    p.ProductIdAuto = np.ID_PRO_AUTO;
                                    p.ProductName = np.NAME_PRO;
                                    p.ProductId = np.ID_PRO;
                                    p.ProductDescription = np.DESCRIPTIONS;                                    
                                    p.SellPrice = np.DETAILS_PRODUCTS.SELL_PRICE??0;
                                    p.CostPrice = np.DETAILS_PRODUCTS.COST_PRICES ?? 0;
                                    p.Unit = new Unit { UnitID = np.DETAILS_PRODUCTS.UNIT.ID_UNIT, UnitName = np.DETAILS_PRODUCTS.UNIT.NAME_UNIT, UnitNote = np.DETAILS_PRODUCTS.UNIT.NOTES_UNIT };
                                    p.catalog = new Catalogs { CatalogName = np.CATALOG.NAME_CATALOG, CatalogNotes = np.CATALOG.NOTES_CATALOG, IDCatalog = np.CATALOG.ID_CATALOG };
                                    p.IsMarble = _exportViewModel.IsMarcle;// phải thêm để xác định sản phẩm mới là Đá Hoa Cương hay k? (11/5)
                                }
                            }
                        }
                    }
                }
                _canExcuteTextChangedEvent = true;
                _exportViewModel.addNewProduct();
            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.Message);
            }
        }

        private void TxtInventoryCountPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!char.IsDigit(e.Text, e.Text.Length - 1))
            {
                e.Handled = true;
            }
        }

        private void TxtInvetoryCountTextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (!IsLoaded)
                    return;
                var textBox = sender as TextBox;
                if (textBox == null) return;
                var pro = textBox.DataContext as Products;
                if (pro != null && (!string.IsNullOrEmpty(pro.ProductName) && pro.InventoryCount > WPFServices.Services.Products.GetProduct(pro.ProductIdAuto).DETAILS_PRODUCTS.INVENTORY_COUNT))

                    if (MessageBox.Show("Số lượng vược quá trong kho! Bạn có muốn lưu hay không?", "Thống báo", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                        pro.InventoryCount = 0;
                        return;
                    }
                // đã chuyển qua xử lý trong set{};
                //pro.totalPayment = pro.InventoryCount * pro.SellPrice;
                CaculationPaymentForAllProduct();
                if (!_exportViewModel.isInNewListProduct(pro))
                {
                    _exportViewModel.IsSaved = false;
                    _exportViewModel.IsChanged = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);throw;
            }
        }

        private void CaculationPaymentForAllProduct()
        {
            try
            {
                _exportViewModel.Payment.SumOut = 0;
                foreach (Products pro in _exportViewModel.ListProducts.Where(pro => !string.IsNullOrEmpty(pro.ProductId)))
                    _exportViewModel.Payment.SumOut += pro.TotalOutPayment;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);throw;
            }
        }

        private void TxtAcceptNumbericPreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!char.IsDigit(e.Text, e.Text.Length - 1))
                e.Handled = true;
        }

        private void TxtProductNameKeydown(object sender, KeyEventArgs e)
        {
            try
            {
                var txt = sender as TextBox;
                if (txt == null) return;
                var p = txt.DataContext as Products;
                if (e.Key != Key.Enter) return;
                var np = WPFServices.Services.Products.GetProductByID(txt.Text);
                if (np == null) return;
                if (p != null)
                {
                    p.ProductIdAuto = np.ID_PRO_AUTO;
                    p.ProductName = np.NAME_PRO;
                    p.ProductId = np.ID_PRO;
                    p.ProductDescription = np.DESCRIPTIONS;
                    if (np.DETAILS_PRODUCTS.COST_PRICES != null)
                        p.CostPrice = (decimal)np.DETAILS_PRODUCTS.COST_PRICES;
                    p.Unit = new Unit { UnitID = np.DETAILS_PRODUCTS.UNIT.ID_UNIT, UnitName = np.DETAILS_PRODUCTS.UNIT.NAME_UNIT, UnitNote = np.DETAILS_PRODUCTS.UNIT.NOTES_UNIT };
                    p.catalog = new Catalogs { CatalogName = np.CATALOG.NAME_CATALOG, CatalogNotes = np.CATALOG.NOTES_CATALOG, IDCatalog = np.CATALOG.ID_CATALOG };
                }
                _exportViewModel.addNewProduct();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        //xử lý lựa chọn loại giá khi check vào checkbox
        private void chboxIsCostPrice_checked(object sender, RoutedEventArgs e)
        {
            if (!IsLoaded)
                return;
            _exportViewModel.IsSaved = false;
            _exportViewModel.IsChanged = true;
            CaculationPaymentForAllProduct();
        }
        
    #endregion

        private void CaculationPayment(object sender, RoutedEventArgs e)
        {
            _exportViewModel.CaculationPaymentForAllProduct();                        
        }

        private void txtDaiRong_textChanged(object sender, TextChangedEventArgs e)
        {
            if (!IsLoaded)
                return;
            try
            {
                var textBox = sender as TextBox;
                if (textBox != null)
                {
                    var pro = textBox.DataContext as Products;
                    if (pro != null && pro.ProductIdAuto > 0)
                    {
                        _exportViewModel.IsChanged = true;
                        _exportViewModel.IsSaved = false;
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }

        

    }
}
